package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"strconv"
	"yukao1/models/redis"
	"yukao1/models/request"
	"yukao1/pkg"
)

// 一对一聊天

type Node struct {
	Conn     *websocket.Conn
	DataRead chan []byte
}

var ClientUser map[int64]*Node = make(map[int64]*Node, 0)
var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
}

func ClientSocket(c *gin.Context) {
	userid := c.Query("userid")
	uid, _ := strconv.Atoi(userid)
	isTsMessage := c.Query("isTsMessage")
	ismess, _ := strconv.Atoi(isTsMessage)
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Println(err)
		return
	}

	node := &Node{
		Conn:     conn,
		DataRead: make(chan []byte, 50),
	}

	//判断是否使用末班
	var mag = []byte("请稍等，正在为您接入客服")
	if ismess != 0 {
		k, ok := ClientUser[int64(uid)]
		if ok {
			k.DataRead <- mag
		}
	}

	ClientUser[int64(uid)] = node
	sendMessage(node) //发送消息
	readMessage(node) //获取消息
}

// 发送消息
func sendMessage(node *Node) {
	go func() {
		for {
			select {
			case data := <-node.DataRead:
				if err := node.Conn.WriteMessage(websocket.TextMessage, data); err != nil {
					log.Println(err)
					return
				}
				//生产者
				simple := pkg.NewRabbitMQSimple("xxz")
				go simple.PublishSimple(string(data))
			}
		}
	}()

}

// 获取消息
func readMessage(node *Node) {
	for {
		_, mag, err := node.Conn.ReadMessage()
		if err != nil {
			log.Println(err)
			return
		}

		//处理消息
		ClMessage(mag)
	}
}

// 处理消息
func ClMessage(mag []byte) {
	var data request.UserSocket
	json.Unmarshal(mag, &data)

	//文本审核

	if !pkg.WbShen(data.DataMessage) {
		fmt.Println("内容不合规")
		data.IsOk = false
		return
	}

	//转发消息
	sendMessageTo(int64(data.OjbectId), mag)
	//储存聊天消息
	marshal, _ := json.Marshal(data)
	redis.RedisSetMessage(data.Userid, data.OjbectId, marshal)
	//消费者
	simple := pkg.NewRabbitMQSimple("xxz")
	go simple.ConsumeSimple()
}

// 转发消息
func sendMessageTo(userid int64, mag []byte) {
	k, ok := ClientUser[userid]
	if ok {
		k.DataRead <- mag
	}

}
